package com.example.demo.SecurityConfig.LoginConfig;

import com.example.demo.Data.User.UserBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

@Component
public class LoginAuthenticationProvider implements AuthenticationProvider
{
    @Qualifier("userDetailServiceImpl")
    @Autowired
    UserDetailsService userDetailsService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException
    {
        String user_id = authentication.getPrincipal().toString();
        String password = authentication.getCredentials().toString();
        UserDetails userDetails = userDetailsService.loadUserByUsername(user_id);
        String correctPassword = userDetails.getPassword();
        if (password.equals(correctPassword))
        {
            if (UserBo.isLoggedin(Long.parseLong(user_id)))
            {
                throw new AlreadyLoggedInException("You have already logged in.");
            }
            else
            {
                UserBo.loginUser(Long.parseLong(user_id));
                return new UsernamePasswordAuthenticationToken(user_id, password, userDetails.getAuthorities());
            }
        }
        else
        {
            throw new BadCredentialsException("Incorrect password.");
        }
    }

    @Override
    public boolean supports(Class<?> aClass)
    {
        return true;
    }
}
